package com.abu.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.abu.auth.client.UserClient;
import com.abu.auth.service.AuthService;
import com.abu.auth.utils.JwtProperties;
import com.abu.auth.utils.JwtUtils;
import com.abu.common.Resp;
import com.abu.common.exception.CRException;
import com.abu.crms.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
@Slf4j
@EnableConfigurationProperties(JwtProperties.class)
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 普通登录
     *
     * @param cardNum
     * @param password
     * @return
     */
    @Override
    public String userAuth(String cardNum, String password) {
//        如果远程服务器不可用时，会直接调用本地的fallback方法
        Resp resp = this.userClient.queryUserInfoByCardNumAndPassword(cardNum, password);
        Integer code = resp.getCode();
        String msg = resp.getMsg();
//        判断是否出错
        if (code == 404 || code == 503 || code == 0) {
            throw new CRException(msg, code);
        }
        LinkedHashMap userMap = (LinkedHashMap) resp.getData().get("user");
        Long userId = (Long) userMap.get("userId");
        String username = (String) userMap.get("username");
        //        token加上UserLogin前缀
        return getToken(userId, username);
    }

    @Override
    public HashMap<String, Object> getUsernameAndImgAndUserId(HttpServletRequest request) {
//        1.获取token
        String token = request.getHeader("token");
//        2.判断token是否为空
        if (StringUtils.isBlank(token)) {
            throw new CRException("token不能为空");
        }
//        3.判断token是否符合规则
        String prefix = "UserLogin";
//        4.获取去掉prefix真正token
        String stripToken = StringUtils.substringAfter(token, prefix);
//        5.获取jwt中的数据（用户名）
        Map<String, Object> infoFromToken = null;
        try {
            infoFromToken = JwtUtils.getInfoFromToken(stripToken, jwtProperties.getPublicKey());
        } catch (Exception e) {
            log.error("jwt获取用户信息失败：{}", e.getMessage());
        }
        String username = (String) infoFromToken.get("username");
        String avatar = (String) infoFromToken.get("avatar");
        Long userId = (Long) infoFromToken.get("userId");
//        6.返回
        HashMap<String, Object> returnData = new HashMap<>(4);
        returnData.put("username", username);
        returnData.put("avatar", avatar);
//        js解析long类型会转为Number类型，出现精度缺失，这是要转为String类型
        returnData.put("userId", String.valueOf(userId));
        return returnData;
    }


    private String getToken(Long userId, String username) {
        //        生成token
//        1.载荷内容
        Map<String, Object> tokenContent = new HashMap<>(1);
        tokenContent.put("userId", userId);
        tokenContent.put("username", username);
//        2.获取私钥
        PrivateKey privateKey = jwtProperties.getPrivateKey();
        int expireTime = jwtProperties.getExpire();
        String token = null;
        try {
            token = JwtUtils.generateToken(tokenContent, privateKey, expireTime * 16);
        } catch (Exception e) {
            log.error("生成token失败，原因为：{}", e.getMessage());
        }
        return "UserLogin" + token;
    }
}
